package com.atguigu.day08;

import com.atguigu.util.Event;
import org.apache.flink.api.common.state.ValueState;
import org.apache.flink.api.common.state.ValueStateDescriptor;
import org.apache.flink.api.common.typeinfo.Types;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.KeyedProcessFunction;
import org.apache.flink.streaming.api.functions.source.SourceFunction;
import org.apache.flink.streaming.api.watermark.Watermark;
import org.apache.flink.util.Collector;

// 超时订单的检测
public class Example8 {
    public static void main(String[] args) {
        var env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);

        var stream = env
                .addSource(new SourceFunction<Event>() {
                    @Override
                    public void run(SourceContext<Event> ctx) {
                        ctx.collectWithTimestamp(new Event("order-1", "pay-order", 4000L), 4000L);
                        ctx.collectWithTimestamp(new Event("order-2", "create-order", 2000L), 2000L);
                        ctx.collectWithTimestamp(new Event("order-1", "create-order", 1000L), 1000L);

                        ctx.emitWatermark(new Watermark(9000L));
                        ctx.collectWithTimestamp(new Event("order-2", "pay-order", 10000L), 10000L);

                        ctx.collectWithTimestamp(new Event("order-3", "create-order", 11000L), 11000L);
                        ctx.collectWithTimestamp(new Event("order-3", "pay-order", 12000L), 12000L);
                    }

                    @Override
                    public void cancel() {

                    }
                });

        stream
                .keyBy(r -> r.key)
                .process(new KeyedProcessFunction<String, Event, String>() {
                    // Tuple2<订单id,订单状态>
                    // 订单状态：
                    //   - create：订单未支付
                    //   - pay：订单已支付
                    //   - timeout： 订单超时未支付
                    private ValueState<Tuple2<String, String>> orderState;

                    @Override
                    public void open(Configuration parameters) {
                        orderState = getRuntimeContext().getState(
                                new ValueStateDescriptor<>(
                                        "order-state",
                                        Types.TUPLE(Types.STRING, Types.STRING)
                                )
                        );
                    }

                    @Override
                    public void processElement(Event value, Context ctx, Collector<String> out) throws Exception {
                        // 第一条事件到达
                        if (orderState.value() == null) {
                            if (value.type.equals("create-order")) {
                                orderState.update(Tuple2.of(value.key, "create"));
                                ctx.timerService().registerEventTimeTimer(value.ts + 5000L);
                            } else if (value.type.equals("pay-order")) {
                                orderState.update(Tuple2.of(value.key, "pay"));
                                out.collect(value.key + "支付成功");
                            }
                        }
                        // 第二条事件到达
                        else {
                            if (value.type.equals("pay-order") && orderState.value().f1.equals("create")) {
                                orderState.update(Tuple2.of(value.key, "pay"));
                                out.collect(value.key + "支付成功");
                            }
                        }
                    }

                    @Override
                    public void onTimer(long timestamp, OnTimerContext ctx, Collector<String> out) throws Exception {
                        // 定时器触发时，我们只检查订单状态是否为“create”
                        if (orderState.value().f1.equals("create")) {
                            out.collect(orderState.value().f0 + "支付失败");
                            orderState.update(Tuple2.of(orderState.value().f0, "timeout"));
                        }
                    }
                })
                .print();

        try {
            env.execute();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
